﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ConsolidationTool.Common;
using Microsoft.SharePoint;
using System.Web.Script.Serialization;

namespace ConsolidationTool.WebParts.Layouts.AjaxServices
{
    public class RateServices
    {

        public List<ExchangeRate> LoadExchangeRate(string inputType, string year, string month) {
            return LoadExchangeRate(inputType, year, month, "Original");
        }
        public List<ExchangeRate> LoadExchangeRate(string inputType, string year, string month, string mode)
        {
            var tmp = new List<ExchangeRate>();

            inputType = inputType == "Flash" ? "Actual" : inputType;

            string exchangeRateListTitle = string.Format("Common_Exchange_Rate_{0}", inputType);
            var list = SPContext.Current.Web.Lists.TryGetList(exchangeRateListTitle);
            if (list == null)
            {
                Utilities.Log("[ExchangeRate] Can not found list : " + exchangeRateListTitle);
                return tmp;
            }
            var query = new SPQuery()
            {
                Query = string.Format(@"   <Where>
      <And>
         <Eq>
            <FieldRef Name='Year' />
            <Value Type='Integer'>{0}</Value>
         </Eq>
         <Eq>
            <FieldRef Name='Month' />
            <Value Type='Integer'>{1}</Value>
         </Eq>
      </And>
   </Where>", year, month)
            };
            if (month.IsNullOrEmpty())
            {
                query = new SPQuery()
                {
                    Query = string.Format(@"   <Where> 
         <Eq>
            <FieldRef Name='Year' />
            <Value Type='Integer'>{0}</Value>
         </Eq> 
   </Where>", year)
                };
            }
            var items = list.GetItems(query);
            int itemCount = items.Count;
            for (int i = 0; i < itemCount; i++)
            {
                var item = items[i];
                string billData = item["BillData"] + "";
                tmp = (new JavaScriptSerializer()).Deserialize<List<ExchangeRate>>(billData);
                tmp.ForEach(p => p.From = string.Format("{0}-{1}", inputType, mode));
            }
            return tmp;
        }
    }
}
